<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    
    <title>Standard array subclasses &mdash; NumPy v1.18 Manual</title>
    
    <link rel="stylesheet" type="text/css" href="../_static/css/spc-bootstrap.css">
    <link rel="stylesheet" type="text/css" href="../_static/css/spc-extend.css">
    <link rel="stylesheet" href="../_static/scipy.css" type="text/css" >
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" >
    <link rel="stylesheet" href="../_static/graphviz.css" type="text/css" >
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.18.1',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  false
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/js/copybutton.js"></script>
    <link rel="author" title="About these documents" href="../about.html" >
    <link rel="index" title="Index" href="../genindex.html" >
    <link rel="search" title="Search" href="../search.html" >
    <link rel="top" title="NumPy v1.18 Manual" href="../index.html" >
    <link rel="up" title="Array objects" href="arrays.html" >
    <link rel="next" title="numpy.matrix.T" href="generated/numpy.matrix.T.html" >
    <link rel="prev" title="Iterating Over Arrays" href="arrays.nditer.html" > 
  </head>
  <body>
<div class="container">
  <div class="top-scipy-org-logo-header" style="background-color: #a2bae8;">
    <a href="../index.html">
      <img border=0 alt="NumPy" src="../_static/numpy_logo.png"></a>
    </div>
  </div>
</div>


    <div class="container">
      <div class="main">
        
	<div class="row-fluid">
	  <div class="span12">
	    <div class="spc-navbar">
              
    <ul class="nav nav-pills pull-left">
        <li class="active"><a href="https://numpy.org/">NumPy.org</a></li>
        <li class="active"><a href="https://numpy.org/doc">Docs</a></li>
        
        <li class="active"><a href="../index.html">NumPy v1.18 Manual</a></li>
        

          <li class="active"><a href="index.html" >NumPy Reference</a></li>
          <li class="active"><a href="arrays.html" accesskey="U">Array objects</a></li> 
    </ul>
              
              
    <ul class="nav nav-pills pull-right">
      <li class="active">
        <a href="../genindex.html" title="General Index"
           accesskey="I">index</a>
      </li>
      <li class="active">
        <a href="generated/numpy.matrix.T.html" title="numpy.matrix.T"
           accesskey="N">next</a>
      </li>
      <li class="active">
        <a href="arrays.nditer.html" title="Iterating Over Arrays"
           accesskey="P">previous</a>
      </li>
    </ul>
              
	    </div>
	  </div>
	</div>
        

	<div class="row-fluid">
      <div class="spc-rightsidebar span3">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Standard array subclasses</a><ul>
<li><a class="reference internal" href="#special-attributes-and-methods">Special attributes and methods</a></li>
<li><a class="reference internal" href="#matrix-objects">Matrix objects</a><ul>
</ul>
</li>
<li><a class="reference internal" href="#memory-mapped-file-arrays">Memory-mapped file arrays</a></li>
<li><a class="reference internal" href="#character-arrays-numpy-char">Character arrays (<code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy.char</span></code>)</a></li>
<li><a class="reference internal" href="#record-arrays-numpy-rec">Record arrays (<code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy.rec</span></code>)</a></li>
<li><a class="reference internal" href="#masked-arrays-numpy-ma">Masked arrays (<code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy.ma</span></code>)</a></li>
<li><a class="reference internal" href="#standard-container-class">Standard container class</a></li>
<li><a class="reference internal" href="#array-iterators">Array Iterators</a><ul>
<li><a class="reference internal" href="#default-iteration">Default iteration</a></li>
<li><a class="reference internal" href="#flat-iteration">Flat iteration</a></li>
<li><a class="reference internal" href="#n-dimensional-enumeration">N-dimensional enumeration</a></li>
<li><a class="reference internal" href="#iterator-for-broadcasting">Iterator for broadcasting</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="arrays.nditer.html"
                        title="previous chapter">Iterating Over Arrays</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="generated/numpy.matrix.T.html"
                        title="next chapter">numpy.matrix.T</a></p>
<div id="searchbox" style="display: none" role="search">
  <h4>Quick search</h4>
    <div>
    <form class="search" action="../search.html" method="get">
      <input type="text" style="width: inherit;" name="q" />
      <input type="submit" value="search" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
          <div class="span9">
            
        <div class="bodywrapper">
          <div class="body" id="spc-section-body">
            
  <div class="section" id="standard-array-subclasses">
<span id="arrays-classes"></span><h1>Standard array subclasses<a class="headerlink" href="#standard-array-subclasses" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Subclassing a <code class="docutils literal notranslate"><span class="pre">numpy.ndarray</span></code> is possible but if your goal is to create
an array with <em>modified</em> behavior, as do dask arrays for distributed
computation and cupy arrays for GPU-based computation, subclassing is
discouraged. Instead, using numpy’s
<a class="reference internal" href="../user/basics.dispatch.html#basics-dispatch"><span class="std std-ref">dispatch mechanism</span></a> is recommended.</p>
</div>
<p>The <a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> can be inherited from (in Python or in C)
if desired. Therefore, it can form a foundation for many useful
classes. Often whether to sub-class the array object or to simply use
the core array component as an internal part of a new class is a
difficult decision, and can be simply a matter of choice. NumPy has
several tools for simplifying how your new object interacts with other
array objects, and so the choice may not be significant in the
end. One way to simplify the question is by asking yourself if the
object you are interested in can be replaced as a single array or does
it really require two or more arrays at its core.</p>
<p>Note that <a class="reference internal" href="generated/numpy.asarray.html#numpy.asarray" title="numpy.asarray"><code class="xref py py-func docutils literal notranslate"><span class="pre">asarray</span></code></a> always returns the base-class ndarray. If
you are confident that your use of the array object can handle any
subclass of an ndarray, then <a class="reference internal" href="generated/numpy.asanyarray.html#numpy.asanyarray" title="numpy.asanyarray"><code class="xref py py-func docutils literal notranslate"><span class="pre">asanyarray</span></code></a> can be used to allow
subclasses to propagate more cleanly through your subroutine. In
principal a subclass could redefine any aspect of the array and
therefore, under strict guidelines, <a class="reference internal" href="generated/numpy.asanyarray.html#numpy.asanyarray" title="numpy.asanyarray"><code class="xref py py-func docutils literal notranslate"><span class="pre">asanyarray</span></code></a> would rarely be
useful. However, most subclasses of the array object will not
redefine certain aspects of the array object such as the buffer
interface, or the attributes of the array. One important example,
however, of why your subroutine may not be able to handle an arbitrary
subclass of an array is that matrices redefine the “*” operator to be
matrix-multiplication, rather than element-by-element multiplication.</p>
<div class="section" id="special-attributes-and-methods">
<h2>Special attributes and methods<a class="headerlink" href="#special-attributes-and-methods" title="Permalink to this headline">¶</a></h2>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><a class="reference internal" href="../user/basics.subclassing.html#basics-subclassing"><span class="std std-ref">Subclassing ndarray</span></a></p>
</div>
<p>NumPy provides several hooks that classes can customize:</p>
<dl class="method">
<dt id="numpy.class.__array_ufunc__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__array_ufunc__</code><span class="sig-paren">(</span><em class="sig-param">ufunc</em>, <em class="sig-param">method</em>, <em class="sig-param">*inputs</em>, <em class="sig-param">**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#numpy.class.__array_ufunc__" title="Permalink to this definition">¶</a></dt>
<dd><div class="versionadded">
<p><span class="versionmodified added">New in version 1.13.</span></p>
</div>
<p>Any class, ndarray subclass or not, can define this method or set it to
None in order to override the behavior of NumPy’s ufuncs. This works
quite similarly to Python’s <code class="docutils literal notranslate"><span class="pre">__mul__</span></code> and other binary operation routines.</p>
<ul class="simple">
<li><p><em>ufunc</em> is the ufunc object that was called.</p></li>
<li><p><em>method</em> is a string indicating which Ufunc method was called
(one of <code class="docutils literal notranslate"><span class="pre">&quot;__call__&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;reduce&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;reduceat&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;accumulate&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;outer&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;inner&quot;</span></code>).</p></li>
<li><p><em>inputs</em> is a tuple of the input arguments to the <code class="docutils literal notranslate"><span class="pre">ufunc</span></code>.</p></li>
<li><p><em>kwargs</em> is a dictionary containing the optional input arguments
of the ufunc. If given, any <code class="docutils literal notranslate"><span class="pre">out</span></code> arguments, both positional
and keyword, are passed as a <a class="reference external" href="https://docs.python.org/dev/library/stdtypes.html#tuple" title="(in Python v3.9)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">tuple</span></code></a> in <em>kwargs</em>. See the
discussion in <a class="reference internal" href="ufuncs.html#ufuncs"><span class="std std-ref">Universal functions (ufunc)</span></a> for details.</p></li>
</ul>
<p>The method should return either the result of the operation, or
<a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.9)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> if the operation requested is not implemented.</p>
<p>If one of the input or output arguments has a <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a>
method, it is executed <em>instead</em> of the ufunc.  If more than one of the
arguments implements <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a>, they are tried in the
order: subclasses before superclasses, inputs before outputs, otherwise
left to right. The first routine returning something other than
<a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.9)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> determines the result. If all of the
<a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a> operations return <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.9)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>, a
<a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.9)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>We intend to re-implement numpy functions as (generalized)
Ufunc, in which case it will become possible for them to be
overridden by the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> method.  A prime candidate is
<a class="reference internal" href="generated/numpy.matmul.html#numpy.matmul" title="numpy.matmul"><code class="xref py py-func docutils literal notranslate"><span class="pre">matmul</span></code></a>, which currently is not a Ufunc, but could be
relatively easily be rewritten as a (set of) generalized Ufuncs. The
same may happen with functions such as <a class="reference internal" href="generated/numpy.median.html#numpy.median" title="numpy.median"><code class="xref py py-func docutils literal notranslate"><span class="pre">median</span></code></a>,
<a class="reference internal" href="generated/numpy.amin.html#numpy.amin" title="numpy.amin"><code class="xref py py-func docutils literal notranslate"><span class="pre">amin</span></code></a>, and <a class="reference internal" href="generated/numpy.argsort.html#numpy.argsort" title="numpy.argsort"><code class="xref py py-func docutils literal notranslate"><span class="pre">argsort</span></code></a>.</p>
</div>
<p>Like with some other special methods in python, such as <code class="docutils literal notranslate"><span class="pre">__hash__</span></code> and
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, it is possible to indicate that your class does <em>not</em>
support ufuncs by setting <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span> <span class="pre">=</span> <span class="pre">None</span></code>. Ufuncs always raise
<a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.9)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> when called on an object that sets
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span> <span class="pre">=</span> <span class="pre">None</span></code>.</p>
<p>The presence of <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a> also influences how
<a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> handles binary operations like <code class="docutils literal notranslate"><span class="pre">arr</span> <span class="pre">+</span> <span class="pre">obj</span></code> and <code class="docutils literal notranslate"><span class="pre">arr</span>
<span class="pre">&lt;</span> <span class="pre">obj</span></code> when <code class="docutils literal notranslate"><span class="pre">arr</span></code> is an <a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> and <code class="docutils literal notranslate"><span class="pre">obj</span></code> is an instance
of a custom class. There are two possibilities. If
<code class="docutils literal notranslate"><span class="pre">obj.__array_ufunc__</span></code> is present and not None, then
<code class="docutils literal notranslate"><span class="pre">ndarray.__add__</span></code> and friends will delegate to the ufunc machinery,
meaning that <code class="docutils literal notranslate"><span class="pre">arr</span> <span class="pre">+</span> <span class="pre">obj</span></code> becomes <code class="docutils literal notranslate"><span class="pre">np.add(arr,</span> <span class="pre">obj)</span></code>, and then
<a class="reference internal" href="generated/numpy.add.html#numpy.add" title="numpy.add"><code class="xref py py-func docutils literal notranslate"><span class="pre">add</span></code></a> invokes <code class="docutils literal notranslate"><span class="pre">obj.__array_ufunc__</span></code>. This is useful if you
want to define an object that acts like an array.</p>
<p>Alternatively, if <code class="docutils literal notranslate"><span class="pre">obj.__array_ufunc__</span></code> is set to None, then as a
special case, special methods like <code class="docutils literal notranslate"><span class="pre">ndarray.__add__</span></code> will notice this
and <em>unconditionally</em> raise <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.9)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>. This is useful if you want to
create objects that interact with arrays via binary operations, but
are not themselves arrays. For example, a units handling system might have
an object <code class="docutils literal notranslate"><span class="pre">m</span></code> representing the “meters” unit, and want to support the
syntax <code class="docutils literal notranslate"><span class="pre">arr</span> <span class="pre">*</span> <span class="pre">m</span></code> to represent that the array has units of “meters”, but
not want to otherwise interact with arrays via ufuncs or otherwise. This
can be done by setting <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span> <span class="pre">=</span> <span class="pre">None</span></code> and defining <code class="docutils literal notranslate"><span class="pre">__mul__</span></code>
and <code class="docutils literal notranslate"><span class="pre">__rmul__</span></code> methods. (Note that this means that writing an
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> that always returns <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.9)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> is not
quite the same as setting <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span> <span class="pre">=</span> <span class="pre">None</span></code>: in the former
case, <code class="docutils literal notranslate"><span class="pre">arr</span> <span class="pre">+</span> <span class="pre">obj</span></code> will raise <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.9)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>, while in the latter
case it is possible to define a <code class="docutils literal notranslate"><span class="pre">__radd__</span></code> method to prevent this.)</p>
<p>The above does not hold for in-place operators, for which <a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>
never returns <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.9)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>.  Hence, <code class="docutils literal notranslate"><span class="pre">arr</span> <span class="pre">+=</span> <span class="pre">obj</span></code> would always
lead to a <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.9)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.  This is because for arrays in-place operations
cannot generically be replaced by a simple reverse operation.  (For
instance, by default, <code class="docutils literal notranslate"><span class="pre">arr</span> <span class="pre">+=</span> <span class="pre">obj</span></code> would be translated to <code class="docutils literal notranslate"><span class="pre">arr</span> <span class="pre">=</span>
<span class="pre">arr</span> <span class="pre">+</span> <span class="pre">obj</span></code>, i.e., <code class="docutils literal notranslate"><span class="pre">arr</span></code> would be replaced, contrary to what is expected
for in-place array operations.)</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>If you define <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>:</p>
<ul class="simple">
<li><p>If you are not a subclass of <a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>, we recommend your
class define special methods like <code class="docutils literal notranslate"><span class="pre">__add__</span></code> and <code class="docutils literal notranslate"><span class="pre">__lt__</span></code> that
delegate to ufuncs just like ndarray does.  An easy way to do this
is to subclass from <a class="reference internal" href="generated/numpy.lib.mixins.NDArrayOperatorsMixin.html#numpy.lib.mixins.NDArrayOperatorsMixin" title="numpy.lib.mixins.NDArrayOperatorsMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">NDArrayOperatorsMixin</span></code></a>.</p></li>
<li><p>If you subclass <a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>, we recommend that you put all your
override logic in <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> and not also override special
methods. This ensures the class hierarchy is determined in only one
place rather than separately by the ufunc machinery and by the binary
operation rules (which gives preference to special methods of
subclasses; the alternative way to enforce a one-place only hierarchy,
of setting <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a> to None, would seem very
unexpected and thus confusing, as then the subclass would not work at
all with ufuncs).</p></li>
<li><p><a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> defines its own <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a>, which,
evaluates the ufunc if no arguments have overrides, and returns
<a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.9)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> otherwise. This may be useful for subclasses
for which <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a> converts any instances of its own
class to <a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>: it can then pass these on to its
superclass using <code class="docutils literal notranslate"><span class="pre">super().__array_ufunc__(*inputs,</span> <span class="pre">**kwargs)</span></code>,
and finally return the results after possible back-conversion. The
advantage of this practice is that it ensures that it is possible
to have a hierarchy of subclasses that extend the behaviour. See
<a class="reference internal" href="../user/basics.subclassing.html#basics-subclassing"><span class="std std-ref">Subclassing ndarray</span></a> for details.</p></li>
</ul>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>If a class defines the <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a> method,
this disables the <a class="reference internal" href="#numpy.class.__array_wrap__" title="numpy.class.__array_wrap__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_wrap__</span></code></a>,
<a class="reference internal" href="#numpy.class.__array_prepare__" title="numpy.class.__array_prepare__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_prepare__</span></code></a>, <a class="reference internal" href="#numpy.class.__array_priority__" title="numpy.class.__array_priority__"><code class="xref py py-data docutils literal notranslate"><span class="pre">__array_priority__</span></code></a> mechanism
described below for ufuncs (which may eventually be deprecated).</p>
</div>
</dd></dl>

<dl class="method">
<dt id="numpy.class.__array_function__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__array_function__</code><span class="sig-paren">(</span><em class="sig-param">func</em>, <em class="sig-param">types</em>, <em class="sig-param">args</em>, <em class="sig-param">kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#numpy.class.__array_function__" title="Permalink to this definition">¶</a></dt>
<dd><div class="versionadded">
<p><span class="versionmodified added">New in version 1.16.</span></p>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<ul class="simple">
<li><p>In NumPy 1.17, the protocol is enabled by default, but can be disabled
with <code class="docutils literal notranslate"><span class="pre">NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=0</span></code>.</p></li>
<li><p>In NumPy 1.16, you need to set the environment variable
<code class="docutils literal notranslate"><span class="pre">NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=1</span></code> before importing NumPy to use
NumPy function overrides.</p></li>
<li><p>Eventually, expect to <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> to always be enabled.</p></li>
</ul>
</div>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">func</span></code> is an arbitrary callable exposed by NumPy’s public API,
which was called in the form <code class="docutils literal notranslate"><span class="pre">func(*args,</span> <span class="pre">**kwargs)</span></code>.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">types</span></code> is a <a class="reference external" href="collections.abc.Collection">collection</a>
of unique argument types from the original NumPy function call that
implement <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>.</p></li>
<li><p>The tuple <code class="docutils literal notranslate"><span class="pre">args</span></code> and dict <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> are directly passed on from the
original call.</p></li>
</ul>
<p>As a convenience for <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementors, <code class="docutils literal notranslate"><span class="pre">types</span></code>
provides all argument types with an <code class="docutils literal notranslate"><span class="pre">'__array_function__'</span></code> attribute.
This allows implementors to quickly identify cases where they should defer
to <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementations on other arguments.
Implementations should not rely on the iteration order of <code class="docutils literal notranslate"><span class="pre">types</span></code>.</p>
<p>Most implementations of <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> will start with two
checks:</p>
<ol class="arabic simple">
<li><p>Is the given function something that we know how to overload?</p></li>
<li><p>Are all arguments of a type that we know how to handle?</p></li>
</ol>
<p>If these conditions hold, <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> should return the result
from calling its implementation for <code class="docutils literal notranslate"><span class="pre">func(*args,</span> <span class="pre">**kwargs)</span></code>.  Otherwise,
it should return the sentinel value <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>, indicating that the
function is not implemented by these types.</p>
<p>There are no general requirements on the return value from
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>, although most sensible implementations should
probably return array(s) with the same type as one of the function’s
arguments.</p>
<p>It may also be convenient to define a custom decorators (<code class="docutils literal notranslate"><span class="pre">implements</span></code>
below) for registering <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementations.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">HANDLED_FUNCTIONS</span> <span class="o">=</span> <span class="p">{}</span>

<span class="k">class</span> <span class="nc">MyArray</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__array_function__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">types</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">func</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">HANDLED_FUNCTIONS</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">NotImplemented</span>
        <span class="c1"># Note: this allows subclasses that don&#39;t override</span>
        <span class="c1"># __array_function__ to handle MyArray objects</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="nb">all</span><span class="p">(</span><span class="nb">issubclass</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">MyArray</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">types</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">NotImplemented</span>
        <span class="k">return</span> <span class="n">HANDLED_FUNCTIONS</span><span class="p">[</span><span class="n">func</span><span class="p">](</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">implements</span><span class="p">(</span><span class="n">numpy_function</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Register an __array_function__ implementation for MyArray objects.&quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">decorator</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
        <span class="n">HANDLED_FUNCTIONS</span><span class="p">[</span><span class="n">numpy_function</span><span class="p">]</span> <span class="o">=</span> <span class="n">func</span>
        <span class="k">return</span> <span class="n">func</span>
    <span class="k">return</span> <span class="n">decorator</span>

<span class="nd">@implements</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">concatenate</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">concatenate</span><span class="p">(</span><span class="n">arrays</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">out</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="o">...</span>  <span class="c1"># implementation of concatenate for MyArray objects</span>

<span class="nd">@implements</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">broadcast_to</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">broadcast_to</span><span class="p">(</span><span class="n">array</span><span class="p">,</span> <span class="n">shape</span><span class="p">):</span>
    <span class="o">...</span>  <span class="c1"># implementation of broadcast_to for MyArray objects</span>
</pre></div>
</div>
<p>Note that it is not required for <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementations to
include <em>all</em> of the corresponding NumPy function’s optional arguments
(e.g., <code class="docutils literal notranslate"><span class="pre">broadcast_to</span></code> above omits the irrelevant <code class="docutils literal notranslate"><span class="pre">subok</span></code> argument).
Optional arguments are only passed in to <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> if they
were explicitly used in the NumPy function call.</p>
<p>Just like the case for builtin special methods like <code class="docutils literal notranslate"><span class="pre">__add__</span></code>, properly
written <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> methods should always return
<code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> when an unknown type is encountered. Otherwise, it will
be impossible to correctly override NumPy functions from another object
if the operation also includes one of your objects.</p>
<p>For the most part, the rules for dispatch with <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>
match those for <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>. In particular:</p>
<ul class="simple">
<li><p>NumPy will gather implementations of <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> from all
specified inputs and call them in order: subclasses before
superclasses, and otherwise left to right. Note that in some edge cases
involving subclasses, this differs slightly from the
<a class="reference external" href="https://bugs.python.org/issue30140">current behavior</a> of Python.</p></li>
<li><p>Implementations of <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> indicate that they can
handle the operation by returning any value other than
<code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>.</p></li>
<li><p>If all <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> methods return <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>,
NumPy will raise <code class="docutils literal notranslate"><span class="pre">TypeError</span></code>.</p></li>
</ul>
<p>If no <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> methods exists, NumPy will default to calling
its own implementation, intended for use on NumPy arrays. This case arises,
for example, when all array-like arguments are Python numbers or lists.
(NumPy arrays do have a <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> method, given below, but it
always returns <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> if any argument other than a NumPy array
subclass implements <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>.)</p>
<p>One deviation from the current behavior of <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> is that
NumPy will only call <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> on the <em>first</em> argument of each
unique type. This matches Python’s <a class="reference external" href="https://docs.python.org/3/reference/datamodel.html#object.__ror__">rule for calling reflected methods</a>, and
this ensures that checking overloads has acceptable performance even when
there are a large number of overloaded arguments.</p>
</dd></dl>

<dl class="method">
<dt id="numpy.class.__array_finalize__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__array_finalize__</code><span class="sig-paren">(</span><em class="sig-param">obj</em><span class="sig-paren">)</span><a class="headerlink" href="#numpy.class.__array_finalize__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called whenever the system internally allocates a
new array from <em>obj</em>, where <em>obj</em> is a subclass (subtype) of the
<a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>. It can be used to change attributes of <em>self</em>
after construction (so as to ensure a 2-d matrix for example), or
to update meta-information from the “parent.” Subclasses inherit
a default implementation of this method that does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="numpy.class.__array_prepare__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__array_prepare__</code><span class="sig-paren">(</span><em class="sig-param">array</em>, <em class="sig-param">context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#numpy.class.__array_prepare__" title="Permalink to this definition">¶</a></dt>
<dd><p>At the beginning of every <a class="reference internal" href="ufuncs.html#ufuncs-output-type"><span class="std std-ref">ufunc</span></a>, this
method is called on the input object with the highest array
priority, or the output object if one was specified. The output
array is passed in and whatever is returned is passed to the ufunc.
Subclasses inherit a default implementation of this method which
simply returns the output array unmodified. Subclasses may opt to
use this method to transform the output array into an instance of
the subclass and update metadata before returning the array to the
ufunc for computation.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>For ufuncs, it is hoped to eventually deprecate this method in
favour of <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="numpy.class.__array_wrap__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__array_wrap__</code><span class="sig-paren">(</span><em class="sig-param">array</em>, <em class="sig-param">context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#numpy.class.__array_wrap__" title="Permalink to this definition">¶</a></dt>
<dd><p>At the end of every <a class="reference internal" href="ufuncs.html#ufuncs-output-type"><span class="std std-ref">ufunc</span></a>, this method
is called on the input object with the highest array priority, or
the output object if one was specified. The ufunc-computed array
is passed in and whatever is returned is passed to the user.
Subclasses inherit a default implementation of this method, which
transforms the array into a new instance of the object’s class.
Subclasses may opt to use this method to transform the output array
into an instance of the subclass and update metadata before
returning the array to the user.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>For ufuncs, it is hoped to eventually deprecate this method in
favour of <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a>.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="numpy.class.__array_priority__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__array_priority__</code><a class="headerlink" href="#numpy.class.__array_priority__" title="Permalink to this definition">¶</a></dt>
<dd><p>The value of this attribute is used to determine what type of
object to return in situations where there is more than one
possibility for the Python type of the returned object. Subclasses
inherit a default value of 0.0 for this attribute.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>For ufuncs, it is hoped to eventually deprecate this method in
favour of <a class="reference internal" href="#numpy.class.__array_ufunc__" title="numpy.class.__array_ufunc__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array_ufunc__</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="numpy.class.__array__">
<code class="sig-prename descclassname">class.</code><code class="sig-name descname">__array__</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">dtype</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#numpy.class.__array__" title="Permalink to this definition">¶</a></dt>
<dd><p>If a class (ndarray subclass or not) having the <a class="reference internal" href="#numpy.class.__array__" title="numpy.class.__array__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array__</span></code></a>
method is used as the output object of an <a class="reference internal" href="ufuncs.html#ufuncs-output-type"><span class="std std-ref">ufunc</span></a>, results will be written to the object
returned by <a class="reference internal" href="#numpy.class.__array__" title="numpy.class.__array__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__array__</span></code></a>. Similar conversion is done on
input arrays.</p>
</dd></dl>

</div>
<div class="section" id="matrix-objects">
<h2>Matrix objects<a class="headerlink" href="#matrix-objects" title="Permalink to this headline">¶</a></h2>
<div class="admonition note" id="index-0">
<p class="admonition-title">Note</p>
<p>It is strongly advised <em>not</em> to use the matrix subclass.  As described
below, it makes writing functions that deal consistently with matrices
and regular arrays very difficult. Currently, they are mainly used for
interacting with <code class="docutils literal notranslate"><span class="pre">scipy.sparse</span></code>. We hope to provide an alternative
for this use, however, and eventually remove the <code class="docutils literal notranslate"><span class="pre">matrix</span></code> subclass.</p>
</div>
<p><a class="reference internal" href="generated/numpy.matrix.html#numpy.matrix" title="numpy.matrix"><code class="xref py py-class docutils literal notranslate"><span class="pre">matrix</span></code></a> objects inherit from the ndarray and therefore, they
have the same attributes and methods of ndarrays. There are six
important differences of matrix objects, however, that may lead to
unexpected results when you use matrices but expect them to act like
arrays:</p>
<ol class="arabic">
<li><p>Matrix objects can be created using a string notation to allow
Matlab-style syntax where spaces separate columns and semicolons
(‘;’) separate rows.</p></li>
<li><p>Matrix objects are always two-dimensional. This has far-reaching
implications, in that m.ravel() is still two-dimensional (with a 1
in the first dimension) and item selection returns two-dimensional
objects so that sequence behavior is fundamentally different than
arrays.</p></li>
<li><p>Matrix objects over-ride multiplication to be
matrix-multiplication. <strong>Make sure you understand this for
functions that you may want to receive matrices. Especially in
light of the fact that asanyarray(m) returns a matrix when m is
a matrix.</strong></p></li>
<li><p>Matrix objects over-ride power to be matrix raised to a power. The
same warning about using power inside a function that uses
asanyarray(…) to get an array object holds for this fact.</p></li>
<li><p>The default __array_priority__ of matrix objects is 10.0, and
therefore mixed operations with ndarrays always produce matrices.</p></li>
<li><p>Matrices have special attributes which make calculations easier.
These are</p>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.matrix.T.html#numpy.matrix.T" title="numpy.matrix.T"><code class="xref py py-obj docutils literal notranslate"><span class="pre">matrix.T</span></code></a></p></td>
<td><p>Returns the transpose of the matrix.</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="generated/numpy.matrix.H.html#numpy.matrix.H" title="numpy.matrix.H"><code class="xref py py-obj docutils literal notranslate"><span class="pre">matrix.H</span></code></a></p></td>
<td><p>Returns the (complex) conjugate transpose of <em class="xref py py-obj">self</em>.</p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.matrix.I.html#numpy.matrix.I" title="numpy.matrix.I"><code class="xref py py-obj docutils literal notranslate"><span class="pre">matrix.I</span></code></a></p></td>
<td><p>Returns the (multiplicative) inverse of invertible <em class="xref py py-obj">self</em>.</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="generated/numpy.matrix.A.html#numpy.matrix.A" title="numpy.matrix.A"><code class="xref py py-obj docutils literal notranslate"><span class="pre">matrix.A</span></code></a></p></td>
<td><p>Return <em class="xref py py-obj">self</em> as an <a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ndarray</span></code></a> object.</p></td>
</tr>
</tbody>
</table>
</li>
</ol>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Matrix objects over-ride multiplication, ‘*’, and power, ‘**’, to
be matrix-multiplication and matrix power, respectively. If your
subroutine can accept sub-classes and you do not convert to base-
class arrays, then you must use the ufuncs multiply and power to
be sure that you are performing the correct operation for all
inputs.</p>
</div>
<p>The matrix class is a Python subclass of the ndarray and can be used
as a reference for how to construct your own subclass of the ndarray.
Matrices can be created from other matrices, strings, and anything
else that can be converted to an <code class="docutils literal notranslate"><span class="pre">ndarray</span></code> . The name “mat “is an
alias for “matrix “in NumPy.</p>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.matrix.html#numpy.matrix" title="numpy.matrix"><code class="xref py py-obj docutils literal notranslate"><span class="pre">matrix</span></code></a>(data[, dtype, copy])</p></td>
<td><p><div class="admonition note">
<p class="admonition-title">Note</p>
<p>It is no longer recommended to use this class, even for linear</p>
</div>
</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="generated/numpy.asmatrix.html#numpy.asmatrix" title="numpy.asmatrix"><code class="xref py py-obj docutils literal notranslate"><span class="pre">asmatrix</span></code></a>(data[, dtype])</p></td>
<td><p>Interpret the input as a matrix.</p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.bmat.html#numpy.bmat" title="numpy.bmat"><code class="xref py py-obj docutils literal notranslate"><span class="pre">bmat</span></code></a>(obj[, ldict, gdict])</p></td>
<td><p>Build a matrix object from a string, nested sequence, or array.</p></td>
</tr>
</tbody>
</table>
<p>Example 1: Matrix creation from a string</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">=</span><span class="n">mat</span><span class="p">(</span><span class="s1">&#39;1 2 3; 4 5 3&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="p">(</span><span class="n">a</span><span class="o">*</span><span class="n">a</span><span class="o">.</span><span class="n">T</span><span class="p">)</span><span class="o">.</span><span class="n">I</span>
<span class="go">[[ 0.2924 -0.1345]</span>
<span class="go"> [-0.1345  0.0819]]</span>
</pre></div>
</div>
<p>Example 2: Matrix creation from nested sequence</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mat</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">10</span><span class="p">],[</span><span class="mf">1.0</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="n">j</span><span class="p">]])</span>
<span class="go">matrix([[  1.+0.j,   5.+0.j,  10.+0.j],</span>
<span class="go">        [  1.+0.j,   3.+0.j,   0.+4.j]])</span>
</pre></div>
</div>
<p>Example 3: Matrix creation from an array</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mat</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">rand</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">))</span><span class="o">.</span><span class="n">T</span>
<span class="go">matrix([[ 0.7699,  0.7922,  0.3294],</span>
<span class="go">        [ 0.2792,  0.0101,  0.9219],</span>
<span class="go">        [ 0.3398,  0.7571,  0.8197]])</span>
</pre></div>
</div>
</div>
<div class="section" id="memory-mapped-file-arrays">
<h2>Memory-mapped file arrays<a class="headerlink" href="#memory-mapped-file-arrays" title="Permalink to this headline">¶</a></h2>
<p id="index-1">Memory-mapped files are useful for reading and/or modifying small
segments of a large file with regular layout, without reading the
entire file into memory. A simple subclass of the ndarray uses a
memory-mapped file for the data buffer of the array. For small files,
the over-head of reading the entire file into memory is typically not
significant, however for large files using memory mapping can save
considerable resources.</p>
<p>Memory-mapped-file arrays have one additional method (besides those
they inherit from the ndarray): <a class="reference internal" href="generated/numpy.memmap.flush.html#numpy.memmap.flush" title="numpy.memmap.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">.flush()</span></code></a> which
must be called manually by the user to ensure that any changes to the
array actually get written to disk.</p>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.memmap.html#numpy.memmap" title="numpy.memmap"><code class="xref py py-obj docutils literal notranslate"><span class="pre">memmap</span></code></a></p></td>
<td><p>Create a memory-map to an array stored in a <em>binary</em> file on disk.</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="generated/numpy.memmap.flush.html#numpy.memmap.flush" title="numpy.memmap.flush"><code class="xref py py-obj docutils literal notranslate"><span class="pre">memmap.flush</span></code></a>(self)</p></td>
<td><p>Write any changes in the array to the file on disk.</p></td>
</tr>
</tbody>
</table>
<p>Example:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">memmap</span><span class="p">(</span><span class="s1">&#39;newfile.dat&#39;</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="nb">float</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">&#39;w+&#39;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="mi">1000</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">10</span><span class="p">]</span> <span class="o">=</span> <span class="mf">10.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">30</span><span class="p">]</span> <span class="o">=</span> <span class="mf">30.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">fromfile</span><span class="p">(</span><span class="s1">&#39;newfile.dat&#39;</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="nb">float</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">b</span><span class="p">[</span><span class="mi">10</span><span class="p">],</span> <span class="n">b</span><span class="p">[</span><span class="mi">30</span><span class="p">]</span>
<span class="go">10.0 30.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">memmap</span><span class="p">(</span><span class="s1">&#39;newfile.dat&#39;</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="nb">float</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">a</span><span class="p">[</span><span class="mi">10</span><span class="p">],</span> <span class="n">a</span><span class="p">[</span><span class="mi">30</span><span class="p">]</span>
<span class="go">10.0 30.0</span>
</pre></div>
</div>
</div>
<div class="section" id="character-arrays-numpy-char">
<h2>Character arrays (<a class="reference internal" href="routines.char.html#module-numpy.char" title="numpy.char"><code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy.char</span></code></a>)<a class="headerlink" href="#character-arrays-numpy-char" title="Permalink to this headline">¶</a></h2>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><a class="reference internal" href="routines.array-creation.html#routines-array-creation-char"><span class="std std-ref">Creating character arrays (numpy.char)</span></a></p>
</div>
<div class="admonition note" id="index-2">
<p class="admonition-title">Note</p>
<p>The <a class="reference internal" href="generated/numpy.chararray.html#numpy.chararray" title="numpy.chararray"><code class="xref py py-obj docutils literal notranslate"><span class="pre">chararray</span></code></a> class exists for backwards compatibility with
Numarray, it is not recommended for new development. Starting from numpy
1.4, if one needs arrays of strings, it is recommended to use arrays of
<a class="reference internal" href="generated/numpy.dtype.html#numpy.dtype" title="numpy.dtype"><code class="xref py py-obj docutils literal notranslate"><span class="pre">dtype</span></code></a> <code class="xref py py-obj docutils literal notranslate"><span class="pre">object_</span></code>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">string_</span></code> or <code class="xref py py-obj docutils literal notranslate"><span class="pre">unicode_</span></code>, and use the free functions
in the <a class="reference internal" href="routines.char.html#module-numpy.char" title="numpy.char"><code class="xref py py-obj docutils literal notranslate"><span class="pre">numpy.char</span></code></a> module for fast vectorized string operations.</p>
</div>
<p>These are enhanced arrays of either <code class="xref py py-class docutils literal notranslate"><span class="pre">string_</span></code> type or
<code class="xref py py-class docutils literal notranslate"><span class="pre">unicode_</span></code> type.  These arrays inherit from the
<a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>, but specially-define the operations <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code>,
and <code class="docutils literal notranslate"><span class="pre">%</span></code> on a (broadcasting) element-by-element basis.  These
operations are not available on the standard <a class="reference internal" href="generated/numpy.ndarray.html#numpy.ndarray" title="numpy.ndarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> of
character type. In addition, the <a class="reference internal" href="generated/numpy.chararray.html#numpy.chararray" title="numpy.chararray"><code class="xref py py-class docutils literal notranslate"><span class="pre">chararray</span></code></a> has all of the
standard <a class="reference external" href="https://docs.python.org/dev/library/stdtypes.html#str" title="(in Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">string</span></code></a> (and <code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code>) methods,
executing them on an element-by-element basis. Perhaps the easiest
way to create a chararray is to use <a class="reference internal" href="generated/numpy.ndarray.view.html#numpy.ndarray.view" title="numpy.ndarray.view"><code class="xref py py-meth docutils literal notranslate"><span class="pre">self.view(chararray)</span></code></a> where <em>self</em> is an ndarray of str or unicode
data-type. However, a chararray can also be created using the
<a class="reference internal" href="generated/numpy.chararray.html#numpy.chararray" title="numpy.chararray"><code class="xref py py-meth docutils literal notranslate"><span class="pre">numpy.chararray</span></code></a> constructor, or via the
<a class="reference internal" href="generated/numpy.core.defchararray.array.html#numpy.core.defchararray.array" title="numpy.core.defchararray.array"><code class="xref py py-func docutils literal notranslate"><span class="pre">numpy.char.array</span></code></a> function:</p>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.chararray.html#numpy.chararray" title="numpy.chararray"><code class="xref py py-obj docutils literal notranslate"><span class="pre">chararray</span></code></a>(shape[, itemsize, unicode, …])</p></td>
<td><p>Provides a convenient view on arrays of string and unicode values.</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="generated/numpy.core.defchararray.array.html#numpy.core.defchararray.array" title="numpy.core.defchararray.array"><code class="xref py py-obj docutils literal notranslate"><span class="pre">core.defchararray.array</span></code></a>(obj[, itemsize, …])</p></td>
<td><p>Create a <a class="reference internal" href="generated/numpy.chararray.html#numpy.chararray" title="numpy.chararray"><code class="xref py py-obj docutils literal notranslate"><span class="pre">chararray</span></code></a>.</p></td>
</tr>
</tbody>
</table>
<p>Another difference with the standard ndarray of str data-type is
that the chararray inherits the feature introduced by Numarray that
white-space at the end of any element in the array will be ignored
on item retrieval and comparison operations.</p>
</div>
<div class="section" id="record-arrays-numpy-rec">
<span id="arrays-classes-rec"></span><h2>Record arrays (<code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy.rec</span></code>)<a class="headerlink" href="#record-arrays-numpy-rec" title="Permalink to this headline">¶</a></h2>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><a class="reference internal" href="routines.array-creation.html#routines-array-creation-rec"><span class="std std-ref">Creating record arrays (numpy.rec)</span></a>, <a class="reference internal" href="routines.dtype.html#routines-dtype"><span class="std std-ref">Data type routines</span></a>,
<a class="reference internal" href="arrays.dtypes.html#arrays-dtypes"><span class="std std-ref">Data type objects (dtype)</span></a>.</p>
</div>
<p>NumPy provides the <a class="reference internal" href="generated/numpy.recarray.html#numpy.recarray" title="numpy.recarray"><code class="xref py py-class docutils literal notranslate"><span class="pre">recarray</span></code></a> class which allows accessing the
fields of a structured array as attributes, and a corresponding
scalar data type object <a class="reference internal" href="generated/numpy.record.html#numpy.record" title="numpy.record"><code class="xref py py-class docutils literal notranslate"><span class="pre">record</span></code></a>.</p>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.recarray.html#numpy.recarray" title="numpy.recarray"><code class="xref py py-obj docutils literal notranslate"><span class="pre">recarray</span></code></a></p></td>
<td><p>Construct an ndarray that allows field access using attributes.</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="generated/numpy.record.html#numpy.record" title="numpy.record"><code class="xref py py-obj docutils literal notranslate"><span class="pre">record</span></code></a></p></td>
<td><p>A data-type scalar that allows field access as attribute lookup.</p></td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="masked-arrays-numpy-ma">
<h2>Masked arrays (<a class="reference internal" href="maskedarray.generic.html#module-numpy.ma" title="numpy.ma"><code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy.ma</span></code></a>)<a class="headerlink" href="#masked-arrays-numpy-ma" title="Permalink to this headline">¶</a></h2>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><a class="reference internal" href="maskedarray.html#maskedarray"><span class="std std-ref">Masked arrays</span></a></p>
</div>
</div>
<div class="section" id="standard-container-class">
<h2>Standard container class<a class="headerlink" href="#standard-container-class" title="Permalink to this headline">¶</a></h2>
<p>For backward compatibility and as a standard “container “class, the
UserArray from Numeric has been brought over to NumPy and named
<a class="reference internal" href="generated/numpy.lib.user_array.container.html#numpy.lib.user_array.container" title="numpy.lib.user_array.container"><code class="xref py py-class docutils literal notranslate"><span class="pre">numpy.lib.user_array.container</span></code></a> The container class is a
Python class whose self.array attribute is an ndarray. Multiple
inheritance is probably easier with numpy.lib.user_array.container
than with the ndarray itself and so it is included by default. It is
not documented here beyond mentioning its existence because you are
encouraged to use the ndarray class directly if you can.</p>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.lib.user_array.container.html#numpy.lib.user_array.container" title="numpy.lib.user_array.container"><code class="xref py py-obj docutils literal notranslate"><span class="pre">numpy.lib.user_array.container</span></code></a>(data[, …])</p></td>
<td><p>Standard container-class for easy multiple-inheritance.</p></td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="array-iterators">
<span id="index-3"></span><h2>Array Iterators<a class="headerlink" href="#array-iterators" title="Permalink to this headline">¶</a></h2>
<p id="index-4">Iterators are a powerful concept for array processing. Essentially,
iterators implement a generalized for-loop. If <em>myiter</em> is an iterator
object, then the Python code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">myiter</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="n">some</span> <span class="n">code</span> <span class="n">involving</span> <span class="n">val</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>calls <code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">next(myiter)</span></code> repeatedly until <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#StopIteration" title="(in Python v3.9)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> is
raised by the iterator. There are several ways to iterate over an
array that may be useful: default iteration, flat iteration, and
<img class="math" src="../_images/math/3bfb3a64189a14b2704f4610827762d5e3145114.svg" alt="N"/>-dimensional enumeration.</p>
<div class="section" id="default-iteration">
<h3>Default iteration<a class="headerlink" href="#default-iteration" title="Permalink to this headline">¶</a></h3>
<p>The default iterator of an ndarray object is the default Python
iterator of a sequence type. Thus, when the array object itself is
used as an iterator. The default behavior is equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">arr</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]):</span>
    <span class="n">val</span> <span class="o">=</span> <span class="n">arr</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
</pre></div>
</div>
<p>This default iterator selects a sub-array of dimension <img class="math" src="../_images/math/f91e7f01955f0d20f5986c6d91696e7f446f669b.svg" alt="N-1"/>
from the array. This can be a useful construct for defining recursive
algorithms. To loop over the entire array requires <img class="math" src="../_images/math/3bfb3a64189a14b2704f4610827762d5e3145114.svg" alt="N"/> for-loops.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">arange</span><span class="p">(</span><span class="mi">24</span><span class="p">)</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">4</span><span class="p">)</span><span class="o">+</span><span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">a</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;item:&#39;</span><span class="p">,</span> <span class="n">val</span>
<span class="go">item: [[10 11 12 13]</span>
<span class="go"> [14 15 16 17]]</span>
<span class="go">item: [[18 19 20 21]</span>
<span class="go"> [22 23 24 25]]</span>
<span class="go">item: [[26 27 28 29]</span>
<span class="go"> [30 31 32 33]]</span>
</pre></div>
</div>
</div>
<div class="section" id="flat-iteration">
<h3>Flat iteration<a class="headerlink" href="#flat-iteration" title="Permalink to this headline">¶</a></h3>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.ndarray.flat.html#numpy.ndarray.flat" title="numpy.ndarray.flat"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ndarray.flat</span></code></a></p></td>
<td><p>A 1-D iterator over the array.</p></td>
</tr>
</tbody>
</table>
<p>As mentioned previously, the flat attribute of ndarray objects returns
an iterator that will cycle over the entire array in C-style
contiguous order.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">val</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">a</span><span class="o">.</span><span class="n">flat</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">i</span><span class="o">%</span><span class="mi">5</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="nb">print</span> <span class="n">i</span><span class="p">,</span> <span class="n">val</span>
<span class="go">0 10</span>
<span class="go">5 15</span>
<span class="go">10 20</span>
<span class="go">15 25</span>
<span class="go">20 30</span>
</pre></div>
</div>
<p>Here, I’ve used the built-in enumerate iterator to return the iterator
index as well as the value.</p>
</div>
<div class="section" id="n-dimensional-enumeration">
<h3>N-dimensional enumeration<a class="headerlink" href="#n-dimensional-enumeration" title="Permalink to this headline">¶</a></h3>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.ndenumerate.html#numpy.ndenumerate" title="numpy.ndenumerate"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ndenumerate</span></code></a>(arr)</p></td>
<td><p>Multidimensional index iterator.</p></td>
</tr>
</tbody>
</table>
<p>Sometimes it may be useful to get the N-dimensional index while
iterating. The ndenumerate iterator can achieve this.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">ndenumerate</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="nb">sum</span><span class="p">(</span><span class="n">i</span><span class="p">)</span><span class="o">%</span><span class="mi">5</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="nb">print</span> <span class="n">i</span><span class="p">,</span> <span class="n">val</span>
<span class="go">(0, 0, 0) 10</span>
<span class="go">(1, 1, 3) 25</span>
<span class="go">(2, 0, 3) 29</span>
<span class="go">(2, 1, 2) 32</span>
</pre></div>
</div>
</div>
<div class="section" id="iterator-for-broadcasting">
<h3>Iterator for broadcasting<a class="headerlink" href="#iterator-for-broadcasting" title="Permalink to this headline">¶</a></h3>
<table class="longtable docutils align-default">
<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="generated/numpy.broadcast.html#numpy.broadcast" title="numpy.broadcast"><code class="xref py py-obj docutils literal notranslate"><span class="pre">broadcast</span></code></a></p></td>
<td><p>Produce an object that mimics broadcasting.</p></td>
</tr>
</tbody>
</table>
<p>The general concept of broadcasting is also available from Python
using the <a class="reference internal" href="generated/numpy.broadcast.html#numpy.broadcast" title="numpy.broadcast"><code class="xref py py-class docutils literal notranslate"><span class="pre">broadcast</span></code></a> iterator. This object takes <img class="math" src="../_images/math/3bfb3a64189a14b2704f4610827762d5e3145114.svg" alt="N"/>
objects as inputs and returns an iterator that returns tuples
providing each of the input sequence elements in the broadcasted
result.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">broadcast</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">],[</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]],[</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">]):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">val</span>
<span class="go">(1, 0)</span>
<span class="go">(0, 1)</span>
<span class="go">(2, 0)</span>
<span class="go">(3, 1)</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
          </div>
        </div>
      </div>
    </div>

    <div class="container container-navbar-bottom">
      <div class="spc-navbar">
        
      </div>
    </div>
    <div class="container">
    <div class="footer">
    <div class="row-fluid">
    <ul class="inline pull-left">
      <li>
        &copy; Copyright 2008-2019, The SciPy community.
      </li>
      <li>
      Last updated on Feb 20, 2020.
      </li>
      <li>
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.4.2.
      </li>
    </ul>
    </div>
    </div>
    </div>
  </body>
</html>